<?php
namespace Models;
class UserModel extends CommonModel {
    public function getUserByUsername($username) {
        $sql = 'select * from users where username = "' . $username . '" limit 1';
        $result = $this->db->query($sql);
        return $result->fetch();
    }

    public function createUser($username, $password) {
        $sql = 'insert into users(username, password) values (:username, :password)';
        $stmt = $this->db->prepare($sql);
        $stmt->bindValue(':username', $username);
        $stmt->bindValue(':password', $password);
        $stmt->execute();
        return $this->db->lastInsertId();
    }

    public function getActiveUser() {
        $sql = 'select user_id, count(*) as count from posts group by user_id order by count desc limit 10';
        $result = $this->db->query($sql)->fetchAll();
        foreach($result as $key => $val) {
            $sql = 'select username from users where id = ' . $val['user_id'];
            $user = $this->db->query($sql)->fetch();
            if (!empty($user)) {
                $result[$key]['username'] = $user['username'];
            } else {
                $result[$key]['username'] = '匿名';
            }
        }
        return $result;
    }
}